package com.dsl.dslallinone.controller;

import com.dsl.dslallinone.common.ApiResponse;
import com.dsl.dslallinone.dto.DslQuery;
import com.dsl.dslallinone.dto.DslQueryResponse;
import com.dsl.dslallinone.service.DslQueryService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * DSL查询控制器
 */
@Tag(name = "DSL查询", description = "DSL查询相关接口")
@RestController
@RequestMapping("/api/dsl")
public class DslQueryController {
    private static final Logger logger = LoggerFactory.getLogger(DslQueryController.class);

    @Autowired
    private DslQueryService dslQueryService;

    /**
     * DSL查询接口
     */
    @Operation(
            summary = "执行DSL查询",
            description = "根据DSL查询条件执行数据查询，支持事实表和实时数据查询",
            requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
                    description = "DSL查询请求参数",
                    required = true,
                    content = @Content(
                            mediaType = "application/json",
                            schema = @Schema(implementation = DslQuery.class),
                            examples = {
                                    @ExampleObject(
                                            name = "基础查询示例",
                                            summary = "查询用水数据",
                                            value = "{" +
                                                    "\"time\": {" +
                                                    "\"window\": {\"start\": \"2025-08-01\", \"end\": \"2025-08-31\"}," +
                                                    "\"granularity\": \"day\"" +
                                                    "}," +
                                                    "\"metrics\": [" +
                                                    "{\"fn\": \"sum\", \"expr\": \"value\", \"as\": \"sum_value\", \"unit\": \"m3\"}" +
                                                    "]," +
                                                    "\"filter\": [" +
                                                    "{\"field\": \"energy_type\", \"op\": \"eq\", \"value\": \"water\"}" +
                                                    "]," +
                                                    "\"groupBy\": [\"building_id\"]," +
                                                    "\"limit\": 100" +
                                                    "}"
                                    ),
                                    @ExampleObject(
                                            name = "同比环比查询",
                                            summary = "查询用电同比环比数据",
                                            value = "{" +
                                                    "\"time\": {" +
                                                    "\"window\": {\"start\": \"2025-07-01\", \"end\": \"2025-07-30\"}," +
                                                    "\"granularity\": \"day\"" +
                                                    "}," +
                                                    "\"metrics\": [" +
                                                    "{\"fn\": \"sum\", \"expr\": \"value\", \"as\": \"sum_value\", \"unit\": \"kWh\"}," +
                                                    "{\"fn\": \"yoy\", \"expr\": \"sum(value)\", \"as\": \"yoy_rate\", \"unit\": \"%\"}," +
                                                    "{\"fn\": \"mom\", \"expr\": \"sum(value)\", \"as\": \"mom_rate\", \"unit\": \"%\"}" +
                                                    "]," +
                                                    "\"filter\": [" +
                                                    "{\"field\": \"energy_type\", \"op\": \"eq\", \"value\": \"electric\"}" +
                                                    "]," +
                                                    "\"groupBy\": [\"building_id\"]," +
                                                    "\"limit\": 1000" +
                                                    "}"
                                    ),
                                    @ExampleObject(
                                            name = "实时数据查询",
                                            summary = "查询实时占用率数据",
                                            value = "{" +
                                                    "\"time\": {" +
                                                    "\"window\": {\"start\": \"2025-01-15\", \"end\": \"2025-01-15\"}," +
                                                    "\"granularity\": \"hour\"" +
                                                    "}," +
                                                    "\"metrics\": [" +
                                                    "{\"fn\": \"avg\", \"expr\": \"occupied\", \"as\": \"avg_occupied\", \"unit\": \"%\"}" +
                                                    "]," +
                                                    "\"filter\": [" +
                                                    "{\"field\": \"floor_id\", \"op\": \"in\", \"value\": [\"101\", \"102\"]}" +
                                                    "]," +
                                                    "\"groupBy\": [\"floor_id\"]," +
                                                    "\"post\": {\"fill_missing\": \"zero\"}," +
                                                    "\"source\": \"realtime\"," +
                                                    "\"limit\": 100" +
                                                    "}"
                                    )
                            }
                    )
            )
    )
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "200",
                    description = "查询成功",
                    content = @Content(
                            mediaType = "application/json",
                            schema = @Schema(implementation = ApiResponse.class)
                    )
            ),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "400",
                    description = "参数错误",
                    content = @Content(mediaType = "application/json")
            ),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "500",
                    description = "服务器内部错误",
                    content = @Content(mediaType = "application/json")
            )
    })
    @PostMapping("/query")
    public ApiResponse<DslQueryResponse> query(
            @Parameter(description = "DSL查询请求参数", required = true)
            @Valid @RequestBody DslQuery query) {
        logger.info("收到DSL查询请求: {}", query);
        
        DslQueryResponse response = dslQueryService.executeQuery(query);
        
        logger.info("DSL查询完成，返回结果");
        return ApiResponse.success(response);
    }
}
